package main

import (
	"fmt"

	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
)

type (
	Order struct {
		Id     int64 `xorm:"id"`
		Status int   `xorm:"status"`
	}
	OrderRoom struct {
		OrderId       int64 `xorm:"order_id"`
		RoomId        int64 `xorm:"room_id"`
		StartTime     int64 `xorm:"start_time"`
		EndTime       int64 `xorm:"end_time"`
		CheckInStatus int   `xorm:"check_in_status"`
		Order         `xorm:"extends"`
		Room          `xorm:"extends"`
	}
	Room struct {
		Id      int64  `xorm:"id"`
		Code    string `xorm:"code"`
		OrderId int64  `xorm:"order_id"`
	}
)

func GetMysqlEngine(uri string) (engine *xorm.Engine, err error) {
	engine, err = xorm.NewEngine("mysql", uri)
	if err != nil {
		return
	}
	engine.SetMaxIdleConns(1)
	engine.SetMaxOpenConns(2)
	return
}

//订单表
func (order Order) TableName() string {
	return "ukm_order"
}

//房间订单关联表
func (orderRoom OrderRoom) TableName() string {
	return "ukm_order_room"
}

//房间表
func (room Room) TableName() string {
	return "ukm_hotel_house_list"
}

//获取房间
func QueryRoom(engine *xorm.Engine, roomId int64) (Room, error) {
	var room Room
	_, err := engine.Where("id=?", roomId).Get(&room)
	return room, err
}

//获取房间最近订单
func (room Room) GetRecentOrderId(engine *xorm.Engine) (int64, error) {
	var order Order
	var orderRoom OrderRoom
	success, err := engine.
		Table(orderRoom.TableName()).
		Join("LEFT", order.TableName(), fmt.Sprintf("%s.id=%s.order_id", order.TableName(), orderRoom.TableName())).
		Where(fmt.Sprintf("%s.room_id=? and %s.status=1", orderRoom.TableName(), order.TableName()), room.Id).
		OrderBy(fmt.Sprintf("%s.start_time desc", orderRoom.TableName())).
		Limit(1, 0).
		Get(&orderRoom)
	if err != nil {
		return -1, err
	} else if success {
		return orderRoom.OrderId, nil
	} else {
		return 0, nil
	}
}

//设置房间最近订单ID
func (room Room) SetRecentOrderId(engine *xorm.Engine, orderId int64) error {
	_, err := engine.Exec(fmt.Sprintf("update %s set order_id=? where id=?", room.TableName()), orderId, room.Id)
	return err
}
